#include <iostream>
#include <thread>
#include <mutex>

class Singleton {
private:
    static Singleton* instance;
    static std::mutex m_mutex;

public:
    static Singleton* getInstance();
};

Singleton* Singleton::instance = nullptr;
std::mutex Singleton::m_mutex;

Singleton* Singleton::getInstance() {
    if (instance == nullptr) {
        std::lock_guard<std::mutex> lock(m_mutex); // 使用std::lock_guard保证线程安全
        if (instance == nullptr) { // 双重检查
            instance = new Singleton();
        }
    }
    return instance;
}

void test() {
    Singleton* s = Singleton::getInstance();
    std::cout << "Thread ID: " << std::this_thread::get_id() << ", Singleton Address: " << s << std::endl;
}

int main() {
    std::thread t1([](){
        for(int i = 0; i < 10000000; ++i)
            test();
    });
    std::thread t2([](){
        Singleton* s = nullptr;
        while(s == nullptr)
            s = Singleton::getInstance();
        std::cout << "Thread " << std::this_thread::get_id() << " got the singleton." << std::endl;
    });
    t1.join();
    t2.join();
    return 0;
}
